﻿using Freebase4net.Rest;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Freebase4net
{
    public class TextService : BaseService<TextServiceResponse>
    {
        protected override string _baseUrl
        {
            get
            {
                return Constants.TextServiceUrl;
            }
        }

        public TextService(string apiKey)
            : base(apiKey)
        {
            this._apiKey = apiKey;
        }

        protected override TextServiceResponse CreateResponse(RestResponseMessage response)
        {
            var freebaseResponse = new TextServiceResponse
            {
                ResultAsString = response.Content,
                Status = response.StatusCode
            };

            if (freebaseResponse.Status == System.Net.HttpStatusCode.OK)
            {
                var obj = JObject.Parse(response.Content);
                var resultList = (string)obj["result"];
                freebaseResponse.Result = resultList;
                freebaseResponse.ResultAsObject = obj;
            }

            return freebaseResponse;
        }

        protected override RestClient CreateRequest(dynamic query)
        {

            RestClient client = new RestClient { BaseUrl = string.Format("{0}{1}", _baseUrl, query) };

            if (!string.IsNullOrEmpty(_apiKey))
            {
                client.AddParameter("key", _apiKey);
            }

            client.RequestFormat = DataFormat.Json;
            return client;

        }

        public TextServiceResponse Read(dynamic query, TextFormat responseFormat = TextFormat.Raw, string language = "/lang/en", int maxLength = 200)
        {
            return ReadInternal(query, GetParams(responseFormat, language, maxLength).ToArray());
        }

        public async Task<TextServiceResponse> ReadAsync(dynamic query, TextFormat responseFormat = TextFormat.Raw, string language = "/lang/en", int maxLength = 200)
        {
            return await ReadInternalAsync(query, GetParams(responseFormat, language, maxLength).ToArray());
        }

        private List<string> GetParams(TextFormat responseFormat, string language, int maxLength)
        {
            List<string> parameters = new List<string>();
            if (responseFormat != TextFormat.Raw)
                parameters.Add(string.Format("format,{0}", ServicesHelpers.GetTextFormat(responseFormat)));
            if (language != "/lang/en")
                parameters.Add(string.Format("lang,{0}", language));
            if (maxLength != 200)
                parameters.Add(string.Format("maxlength,{0}", maxLength));
            return parameters;
        }
    }
}
